<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="order-page-container">
                <div class="idle-info-container" @click="toDetails(orderInfo.idleItem.id)">
                    <el-image
                            style="width: 150px; height: 150px;"
                            :src="orderInfo.idleItem.imgUrl"
                            fit="cover"></el-image>
                    <div class="idle-info-title">{{orderInfo.userId==userId?'买到的':'卖出的'}}：{{orderInfo.idleItem.idleName}}</div>
                    <div class="idle-info-price">￥{{orderInfo.orderPrice}}</div>

                </div>
                <div class="address-container" @click.stop="selectAddressDialog" :style="orderInfo.userId==userId&&orderInfo.orderStatus===0?'cursor: pointer;':''">
                    <div class="address-title">收货地址: {{addressInfo.consigneeName}} {{addressInfo.consigneePhone}}</div>
                    <div class="address-detials">{{addressInfo.detailAddress}}</div>
                    <el-button v-if="!addressInfo.detailAddress" @click.stop="selectAddressDialog" type="primary" plain>选择收货地址</el-button>
                </div>
                <el-dialog
                        title="选择地址"
                        :visible.sync="addressDialogVisible"
                        width="800px">
                    <el-table
                            stripe
                            empty-text="无地址信息，请先在个人中心添加地址"
                            :data="addressData"
                            style="width: 100%">
                        <el-table-column
                                prop="consigneeName"
                                label="收货人姓名"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                prop="consigneePhone"
                                label="手机号"
                                width="140">
                        </el-table-column>
                        <el-table-column
                                prop="detailAddressText"
                                label="地址">
                        </el-table-column>
                        <el-table-column label=" " width="120">
                            <template slot-scope="scope">
                                <el-button
                                        size="mini"
                                        @click="selectAddress(scope.$index, scope.row)">选择
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-dialog>
                <div class="order-info-container">
                    <div class="order-info-title">订单信息（{{orderStatus[orderInfo.orderStatus]}}）：</div>
                    <div class="order-info-item">编号：{{orderInfo.orderNumber}}</div>
                    <div class="order-info-item">支付状态：{{orderInfo.paymentStatus===0?'未支付':'已支付'}}</div>
                    <div class="order-info-item">支付方式：{{orderInfo.paymentWay}}</div>
                    <div class="order-info-item">创建时间：{{ formatTime(orderInfo.createTime) }}
                    </div>
                    <div class="order-info-item">支付时间：{{ formatTime(orderInfo.paymentTime) }}
                    </div>
                      <div class="order-info-item" v-if="orderInfo.orderStatus === 0">
                            支付剩余时间：<span :style="timeLeft <= 60 ? 'color: red;' : ''">{{ formatCountdown(timeLeft) }}</span>
                        </div>
                </div>
                <div class="menu">
                    <el-button v-if="userId==orderInfo.userId&&orderInfo.orderStatus===0" type="danger" plain @click="changeOrderStatus(4,orderInfo)">取消订单</el-button>
                    <el-button v-if="userId==orderInfo.userId&&orderInfo.orderStatus===0" type="primary" plain @click="changeOrderStatus(1,orderInfo)">立即支付</el-button>
                    <el-button v-if="userId==orderInfo.idleItem.userId&&orderInfo.orderStatus===1" type="primary" plain @click="changeOrderStatus(2,orderInfo)">发货</el-button>
                    <el-button v-if="userId==orderInfo.userId&&orderInfo.orderStatus===2" type="primary" plain @click="changeOrderStatus(3,orderInfo)">确认收货</el-button>
                    <!-- 新增退货按钮 -->
                    <el-button v-if="userId==orderInfo.userId&&(orderInfo.orderStatus===2||orderInfo.orderStatus===3)" type="warning" plain @click="applyForReturn(orderInfo)">申请退货</el-button>
                    <el-button 
                        v-if="userId==orderInfo.idleItem.userId&&orderInfo.orderStatus===5" 
                        type="warning" 
                        plain 
                        @click="showRefundDialog(orderInfo)">
                        处理退货退款
                    </el-button>
                </div>
                 <!-- 新增退款对话框 -->
    <el-dialog title="处理退货退款" :visible.sync="refundDialogVisible" width="500px">
        <el-form :model="refundForm" label-width="100px">
            <el-form-item label="退款金额">
                <el-input v-model="refundForm.refundAmount" :placeholder="'最大可退: '+orderInfo.orderPrice"></el-input>
            </el-form-item>
            <el-form-item label="退款原因">
                <el-input type="textarea" v-model="refundForm.refundReason"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer">
            <el-button @click="refundDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="processRefund(orderInfo)">确认退款</el-button>
        </span>
    </el-dialog>
            </div>
        </app-body>
    </div>
</template>

<script>
    import AppHead from '../common/AppHeader.vue';
    import AppBody from '../common/AppPageBody.vue'
    import AppFoot from '../common/AppFoot.vue'
import dayjs from 'dayjs';
    export default {
        name: "order",
        components: {
            AppHead,
            AppBody,
            AppFoot
        },
        data() {
            return {
                timeLeft: 900, // 剩余秒数
                refundDialogVisible: false,
            refundForm: {
                refundAmount: '',
                refundReason: ''
            },
                addressDialogVisible:false,
                addressData: [],
                orderStatus: ['待付款', '待发货', '待收货', '已完成', '已取消', '退货中', '已退货'],
                orderInfo: {
                    createTime: "",
                    id: 0,
                    idleId: 0,
                    idleItem: {
                        id: '',
                        idleName: '',
                        idleDetails: '',
                        pictureList: [],
                        idlePrice: 0,
                        idlePlace: '',
                        idleLabel: '',
                        idleStatus: -1,
                        userId: '',
                    },
                    orderNumber: "",
                    orderPrice: 0,
                    orderStatus: 0,
                    paymentStatus: 0,
                    paymentTime: "",
                    paymentWay: "",
                    userId: 0
                },
                addressInfo: {
                    id:'',
                    update:false,
                    consigneeName: '',
                    consigneePhone: '',
                    detailAddress: ''
                },
                userId:''
            };
        },
        created() {
            // 使用JWT令牌认证，从本地存储获取用户信息
            const token = localStorage.getItem('token');
            
            if (!token) {
                this.$message.error('用户未登录或登录已过期');
                this.$router.push('/login');
                return;
            }
            
            // 获取用户信息
            this.$api.getUserInfo().then(res => {
                console.log("Order的信息:",res.status_code,"Order的res.data",res.data,"Order的res.data.user",res.data.user);
                if (res.status_code === 1 && res.data && res.data.id) {
                    this.userId = res.data.id;
                    console.log('userId', this.userId);
                    this.loadOrderData();
                } else {
                    this.$message.error('获取用户信息失败');
                    this.$router.push('/login');
                }
            }).catch(err => {
                console.error('获取用户信息失败', err);
                this.$message.error('获取用户信息失败');
                this.$router.push('/login');
            });
        },
        methods: {
                // 格式化显示
    formatCountdown(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
            // 计算剩余时间
    startCountdown(expiresAt) {
      if (this.countdownTimer) clearInterval(this.countdownTimer);
      
      const expireTime = new Date(expiresAt);
      if (isNaN(expireTime.getTime())) {
        console.error('无效的过期时间:', expiresAt);
        return;
      }

      this.updateTimeLeft(expireTime);
      this.countdownTimer = setInterval(() => this.updateTimeLeft(expireTime), 1000);
    },
    updateTimeLeft(expireTime) {
      const now = new Date();
      this.timeLeft = Math.max(0, Math.floor((expireTime - now) / 1000));
      console.log('剩余时间:', this.timeLeft); // 调试
      
      if (this.timeLeft <= 0) {
        clearInterval(this.countdownTimer);
        this.$message.warning('订单已超时，请重新下单');
        this.orderInfo.orderStatus = 4;
      }
    },
            formatTime(time) {
    if (!time) return ''; // 处理空值
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
},
            // 显示退款对话框
        showRefundDialog(orderInfo) {
            this.refundForm.refundAmount = orderInfo.orderPrice;
            this.refundDialogVisible = true;
        },
        
        // 处理退款请求
        async processRefund(orderInfo) {
            if (!this.checkAuth()) return;
            
            if (this.refundForm.refundAmount <= 0) {
                this.$message.error('退款金额必须大于0');
                return;
            }
            
            this.$confirm('确认要执行退款操作吗？', '退款确认', {
                confirmButtonText: '确认退款',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const loading = this.$loading({
                        lock: true,
                        text: '正在处理退款...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    
                    // 调用退款API
                    const res = await this.$api.processRefund({
                        orderId: orderInfo.id,
                        orderNumber: orderInfo.orderNumber,
                        idleId: orderInfo.idleId,
                        refundAmount: this.refundForm.refundAmount,
                        refundReason: this.refundForm.refundReason || '用户退货'
                    });
                    
                    loading.close();
                    
                    if (res.status_code === 1) {
                        this.$message.success('退款成功！');
                        this.refundDialogVisible = false;
                        // 刷新订单数据
                        this.loadOrderData();
                    } else {
                        this.$message.error(res.msg || '退款失败');
                    }
                } catch (error) {
                    console.error("退款失败:", error);
                    this.$message.error('退款处理失败，请重试');
                }
            }).catch(() => {
                this.$message.info('已取消退款操作');
            });
        },
            // 加载订单数据的方法
            // 修改加载订单方法
    async loadOrderData() {
      try {
        const res = await this.$api.getOrder({ id: this.$route.query.id });
        if (res.status_code === 1) {
          this.orderInfo = res.data;
          console.log('订单数据:', res.data); // 调试
          if (this.orderInfo.orderStatus === 0 && this.orderInfo.expiresAt) {
            this.startCountdown(this.orderInfo.expiresAt);
          }
        }
      } catch (err) {
        console.error('获取订单失败', err);
      }
    },
            // 检查JWT令牌是否有效
            checkAuth() {
                const token = localStorage.getItem('token');
                if (!token) {
                    this.$message.error('用户未登录或登录已过期');
                    this.$router.push('/login');
                    return false;
                }
                return true;
            },
            
            toDetails(id) {
                if (this.checkAuth()) {
                    this.$router.replace({path: 'details', query: {id: id}});
                }
            },
            selectAddressDialog(){
                if (!this.checkAuth()) return;
                
                if(this.orderInfo.userId==this.userId&&this.orderInfo.orderStatus===0){
                    this.addressDialogVisible=true;
                    if(this.addressData.length===0){
                        this.getAddressData();
                    }
                }
            },
            getAddressData(){
                if (!this.checkAuth()) return;
                
                this.$api.getAddress().then(res => {
                    if (res.status_code === 1) {
                        let data = res.data;
                        for (let i = 0; i < data.length; i++) {
                            data[i].detailAddressText = data[i].provinceName + data[i].cityName + data[i].regionName + data[i].detailAddress;
                        }
                        console.log(data);
                        this.addressData = data;
                        if(!this.addressInfo.update){
                            for(let i=0;i<data.length;i++){
                                if(data[i].defaultFlag){
                                    this.selectAddress(i,data[i]);
                                }
                            }
                        }
                    }
                })
            },
            selectAddress(i,item){
                if (!this.checkAuth()) return;
                
                this.addressDialogVisible=false;
                console.log(item,this.addressInfo);
                this.addressInfo.consigneeName=item.consigneeName;
                this.addressInfo.consigneePhone=item.consigneePhone;
                this.addressInfo.detailAddress=item.detailAddressText;
                if(this.addressInfo.update){
                    this.$api.updateOrderAddress({
                        id:this.addressInfo.id,
                        consigneeName:item.consigneeName,
                        consigneePhone:item.consigneePhone,
                        detailAddress:item.detailAddressText
                    })
                }else{
                    this.$api.addOrderAddress({
                        orderId:this.orderInfo.id,
                        consigneeName:item.consigneeName,
                        consigneePhone:item.consigneePhone,
                        detailAddress:item.detailAddressText
                    }).then(res=>{
                        if(res.status_code===1){
                            this.addressInfo.update=true;
                            this.addressInfo.id=res.data.id;
                        }else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            },
            
            // 新增的申请退货方法
            applyForReturn(orderInfo) {
                if (!this.checkAuth()) return;
                
                this.$confirm('确定要申请退货吗？', '申请退货', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    try {
                        const res = await this.$api.updateOrder({
                            id: orderInfo.id,
                            orderStatus: 5 // 5表示退货中
                        });

                        if (res.status_code === 1) {
                            this.orderInfo.orderStatus = 5;
                            this.$message.success('退货申请已提交，等待卖家处理！');
                        } else {
                            this.$message.error(res.msg || '申请退货失败');
                        }
                    } catch (error) {
                        console.error("申请退货失败：", error);
                        this.$message.error('申请退货失败，请重试！');
                    }
                }).catch(() => {
                    this.$message.info('已取消退货申请');
                });
            },
            
            changeOrderStatus(orderStatus, orderInfo) {
                if (!this.checkAuth()) return;

                // 支付订单逻辑（orderStatus === 1）
                if (orderStatus === 1) {
                    
                    if (!this.addressInfo.detailAddress) {
                        this.$message.error('请选择地址！');
                        return;
                    }
                    if (this.timeLeft <= 0) {
                    this.$message.error('订单已超时，请重新下单');
                    return;
                    }
                    this.$confirm('模拟支付宝支付，是否确认支付', '支付订单', {
                        confirmButtonText: '支付',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            // 调用支付宝沙盒支付
                            console.log("调用支付宝沙盒支付")
                            const payRes = await this.reqPay({ 
                                comit: true 
                            }, {
                                idleId: orderInfo.idleItem.id,
                                idleItem: orderInfo.idleItem,
                                id: orderInfo.id,
                                orderStatus,
                                paymentStatus: 1,
                                paymentWay: '支付宝',
                            });

                            console.log("支付结果为：", payRes);
                            
                            if (payRes.status_code === 1) {
                                console.log("支付成功！更新本地状态...")
                                // 支付成功后更新本地状态
                                this.orderInfo.orderStatus = orderStatus;
                                this.orderInfo.paymentStatus = 1;
                                this.orderInfo.paymentWay = '支付宝';
                                this.orderInfo.paymentTime = this.formatTime(payRes.data.paymentTime);

                                // 同步更新服务器订单状态
                                const updateRes = await this.$api.updateOrder({
                                    id: orderInfo.id,
                                    orderStatus,
                                    paymentTime: payRes.data.paymentTime,
                                    paymentWay: '支付宝',
                                    paymentStatus: 1
                                });
                                if (updateRes.status_code !== 1) {
                                    this.$message.error('支付失败！更新表格数据失败!');
                                }
                                console.log("更新订单结果为：", updateRes);
                                this.$message.success('支付成功！');
                            }
                        } catch (error) {
                            console.error("支付流程异常：", error);
                            this.$message.error(`支付失败：${error.message}`);
                        }
                    }).catch(() => {
                        this.$message.info('已取消支付操作');
                    });
                } 
                // 发货逻辑（orderStatus === 2）
                else if (orderStatus === 2) {
                    this.$confirm('确认要发货吗？', '发货确认', {
                        confirmButtonText: '确认发货',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            const res = await this.$api.updateOrder({
                                id: orderInfo.id,
                                orderStatus: orderStatus
                            });

                            if (res.status_code === 1) {
                                this.orderInfo.orderStatus = orderStatus;
                                this.$message.success('发货成功！');
                            } else {
                                this.$message.error(res.msg || '发货失败');
                            }
                        } catch (error) {
                            console.error("发货失败：", error);
                            this.$message.error('发货失败，请重试！');
                        }
                    }).catch(() => {
                        this.$message.info('已取消发货操作');
                    });
                }
                // 确认收货逻辑（orderStatus === 3）
                else if (orderStatus === 3) {
                    this.$confirm('确认已收到商品吗？', '确认收货', {
                        confirmButtonText: '确认收货',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            const res = await this.$api.updateOrder({
                                id: orderInfo.id,
                                orderStatus: orderStatus
                            });

                            if (res.status_code === 1) {
                                this.orderInfo.orderStatus = orderStatus;
                                this.$message.success('确认收货成功！');
                            } else {
                                this.$message.error(res.msg || '确认收货失败');
                            }
                        } catch (error) {
                            console.error("确认收货失败：", error);
                            this.$message.error('确认收货失败，请重试！');
                        }
                    }).catch(() => {
                        this.$message.info('已取消收货操作');
                    });
                }
                // 取消订单逻辑（orderStatus === 4）
                else if (orderStatus === 4) {
                    this.$confirm('确认要取消订单吗？', '取消订单', {
                        confirmButtonText: '确认取消',
                        cancelButtonText: '暂不取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            const res = await this.$api.updateOrder({
                                id: orderInfo.id,
                                orderStatus: orderStatus
                            });

                            if (res.status_code === 1) {
                                this.orderInfo.orderStatus = orderStatus;
                                this.$message.success('订单已成功取消！');
                            } else {
                                this.$message.error(res.msg || '取消订单失败');
                            }
                        } catch (error) {
                            console.error("取消订单失败：", error);
                            this.$message.error('订单取消失败，请重试！');
                        }
                    }).catch(() => {
                        this.$message.info('已取消操作');
                    });
                }
                // 处理退货完成逻辑（orderStatus === 6）
                else if (orderStatus === 6) {
                    this.$confirm('确认已完成退货流程吗？', '完成退货', {
                        confirmButtonText: '确认完成',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            const res = await this.$api.updateOrder({
                                id: orderInfo.id,
                                orderStatus: orderStatus
                            });

                            if (res.status_code === 1) {
                                this.orderInfo.orderStatus = orderStatus;
                                this.$message.success('退货流程已完成！');
                            } else {
                                this.$message.error(res.msg || '完成退货失败');
                            }
                        } catch (error) {
                            console.error("完成退货失败：", error);
                            this.$message.error('完成退货失败，请重试！');
                        }
                    }).catch(() => {
                        this.$message.info('已取消操作');
                    });
                }
            },
            async reqPay({comit},data)
            {
                console.log("支付结果为：",result);
                let result=await this.$api.reqAliPay(data);
                const blob =new Blob([result],{type:'text/html'});
                const url =URL.createObjectURL(blob);
                window.open(url,'_self');
            },
              beforeDestroy() {
    if (this.countdownTimer) clearInterval(this.countdownTimer);
  }
            
        }
    }
</script>

<style scoped>
    .order-page-container {
        min-height: 85vh;
    }

    .idle-info-container {
        width: 100%;
        display: flex;
        border-bottom: 20px solid #f6f6f6;
        padding: 20px;
        cursor: pointer;
    }

    .idle-info-title {
        font-size: 18px;
        font-weight: 600;
        max-width: 750px;
        margin-left: 10px;
    }

    .idle-info-price {
        font-size: 18px;
        color: red;
        margin-left: 10px;
    }

    .address-container {
        min-height: 60px;
        padding: 20px;
        border-bottom: 20px solid #f6f6f6;

    }

    .address-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 10px;
    }

    .address-detials {
        font-size: 16px;
        color: #444444;
    }

    .order-info-container {
        padding: 20px;
    }

    .order-info-item {
        margin: 10px 0;
        font-size: 14px;
        color: #444444;
    }

    .menu {
        margin-left: 20px;
    }
</style>